<template>
  <div class="login">
    <div class="login-form">
      <el-form :model="loginForm" :rules="loginRules" ref="loginForm">
        <el-form-item prop="username">
          <el-input v-model="loginForm.username" placeholder="账号:admin" prefix-icon="el-icon-user" clearable></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="loginForm.password" type="password" placeholder="密码:admin" prefix-icon="el-icon-lock" @keyup.enter.native="onSubmit" clearable></el-input>
        </el-form-item>
        <el-form-item prop="captcha" style="position: relative">
          <el-input v-model="loginForm.captcha" style="width: 60%"  placeholder="请输入验证码" @keyup.enter.native="onSubmit" clearable></el-input>
          <img class="login-captcha" :src="captchaUrl" @click="changeCaptcha"/>
        </el-form-item>
        <el-form-item>
          <el-button class="login-button" type="primary" @click="onSubmit">登录</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
export default {
  name: "Login",
  data () {
    return {
      captchaUrl: window.captchaUrl,
      loginForm: {
        username: '',
        password: '',
        captcha: ''
      },
      loginRules: {
        username: [{ required: true, message: '必填', trigger: 'blur' }],
        password: [{ required: true, message: '必填', trigger: 'blur' }],
        captcha: [{ required: true, message: '必填', trigger: 'blur' }]
      }
    }
  },
  methods: {
    changeCaptcha () {
      this.captchaUrl = window.captchaUrl + '?time=' + Date.now();
    },
    onSubmit () {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          const loginURL = `/login?username=${this.loginForm.username}&password=${this.loginForm.password}&captcha=${this.loginForm.captcha}`
          this.$axios.post(loginURL).then(res => {
            if (res.code === 200) {
              this.$router.replace('/')
            }
          })
        }
      })
    }
  },
  mounted() {
  }
}
</script>

<style lang="scss" scoped>
  .login {
    width: 100%;
    height: 100%;
    background-image: url("../assets/images/login.svg");
    background-repeat: no-repeat;
    background-size: 100% 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    .login-form {
      width: 336px;
      height: 408px;
      background-color: #ffffff;
      border-radius: 12px;
      box-sizing: border-box;
      display: flex;
      flex-direction: column;
      justify-content: space-around;
      padding: 40px;
      .login-captcha {
        position: absolute;
        right: 0;
        bottom: 0;
        width: 100px;
        height: 40px;
        border-radius: 4px;
      }
      .login-button {
        width: 100%;
      }
    }
  }
</style>
